<?php
// +----------------------------------------------------------------------
// | duoduojie app system
// +----------------------------------------------------------------------
// | Copyright (c) 2017 duoduojie app All rights reserved.
// +----------------------------------------------------------------------
// | Author: Gooe <zqscjj@163.com> QQ:81009953
// +----------------------------------------------------------------------
namespace app\api\controller;

use think\Controller;
/**
 * 产品列表，搜索
 * @author zqs
 *
 */
class Lists extends Controller
{
    /**
     * 产品列表，暂不做限制处理
     * {@inheritDoc}
     * @see \app\common\controller\Api::initialize()
     */
    public function initialize()
    {
        parent::initialize();
    }
    
    /**
     * 版块信息  v1.1
     * type 0 全部，1首页，2精品推荐
     */
    public function section(){
        $type = intval(input('type',0));
        $map = [['status','=',1]];
        if ($type==1){
            $map[] = ['is_index','=',1];
        }elseif ($type==2){
            $map[] = ['is_jinping','=',1];
        }
        $list = db('goods_section')->where($map)->order('sort desc')->field('id,name')->select();
        if ($list){
            $this->success('获取成功','',$list);
        }else {
            $this->error('获取失败');
        }
    }
    /**
     * 版块下的产品 v1.1
     */
    public function section_goods(){
        //获取配置
        $db_config = get_db_config(true);
        $lvcfg = $db_config['user_leval_cfg'];
        $config = [];
        $id = intval(input('id',0));
        $p = intval(input('p',1));
        $map = [];
        $order = $db_config['app_goods_default_sort']??'id desc';
        $section = db('goods_section')->where('status',1)->where('id',$id)->find();
        if ($section){
            $order = $section['sort_type'];
            $map[] = ['section_id','=',$id];
            //过滤销量和佣金是否天猫
            $map[] = ['sales','>',$section['filter_volume']];
            $map[] = ['rate','>',$section['filter_yj']];
            if ($section['user_type']!=0){
                $map[] = ['is_tmall','=',$section['user_type']-1];
            }
        }
        //主动排序
        $sort_type = input('sort','default');
        $desc = input('desc','asc');
        $is_tmall = input('is_tmall',0);
        $q = input('q','');
        if (isset($is_tmall)){
            $map[] = ['is_tmall','=',$is_tmall];
        }
        if (!empty($q)){
            $map[]= ['title','like',"%{$q}%"];
        }
        //排序
        if ($sort_type=='sales'){//销量排序
            $order = "sales ".($desc=='up'?'asc':'desc');
        }elseif ($sort_type=='price'){//价格排序
            $order = "price_after_quan ".($desc=='up'?'asc':'desc');
        }elseif ($sort_type=='quan_price'){
            $order = "quan_price ".($desc=='up'?'asc':'desc');
        }elseif ($sort_type=='rate'){
            $order = "rate_price ".($desc=='up'?'asc':'desc');
        }elseif ($sort_type=='is_tmall'){
            $map[] = ['is_tmall','=',1];
        }
        //是否默认10大分类
        $cid = (int)input('cid');
        if ($cid>0 && $cid<=10){
            $map[] = ['cid','=',$cid];
        }
        //查询
        $list = model('Goods')
        ->where($map)
        ->whereTime('quan_end_time','>',time())
        //->field('from',true)
        ->field('id,price_after_quan*rate as rate_price,item_id,title,short_title,pic,price,rate,price_after_quan,sales,quan_price,is_tmall,quan_total,quan_shengyu,quan_start_time,quan_end_time')//统一标准输出
        ->orderRaw($order)
        ->page($p,10)
        ->select();
        $list->append(['is_tmall_text']);
        //是否带有登录信息
        $token = input('token');
        $uid = input('uid');
        $uinfo = model('User')->get(['uid'=>$uid,'token'=>$token]);
        $leval = 0;
        if ($uinfo){
            $leval = $uinfo->getData('leval');
        }
        $zi_cfg = $lvcfg['zigou'];
        //解决图片可能没有https
        foreach ($list as $k=>$v){
            if (strpos($v['pic'], 'https:')===false&&strpos($v['pic'], 'http:')===false){
                $list[$k]['pic'] = 'https:'.$v['pic'];
            }
            $list[$k]['pic'] = $list[$k]['pic'];//.'_200x200.jpg';
            $list[$k]['coupon_start_time'] = date('Y-m-d',strtotime($v['quan_start_time']));
            $list[$k]['coupon_end_time'] = date('Y-m-d',strtotime($v['quan_end_time']));
            $list[$k]['coupon_total_count'] = $v['quan_total'];
            $list[$k]['coupon_remain_count'] = $v['quan_shengyu'];
            
            //预估赚以及升级赚,取自购
            $earn_yg = 0;
            if ($leval>=0){
                $earn_yg = round($v['price_after_quan']*$v['rate']*$zi_cfg[$leval]/10000,2);
            }
            //升级赚,直接取分公司
            $list[$k]['earn_sj'] = round($v['price_after_quan']*$v['rate']*$zi_cfg[3]/10000,2);
            $list[$k]['earn_yg'] = $earn_yg;
            
        }
        $return = [
            'data' => $list,
            'config' => $config
        ];
        $list = $list ?? [];
        if (count($list)>0){
            $this->success('获取成功','',$return);
        }
        $this->error('没有啦,不开森-_-!');
    }
    /**
     * 搜索
     */
    public function search()
    {
        $tjp = input('tjp','t');
        $re = false;
        switch ($tjp){
            case 't':
                $re = $this->taobao();
                break;
            case 'j':
                $re = $this->jd();
                break;
            case 'p':
                $re = $this->pdd();
                break;
            default:
                $re = $this->taobao();
        }
        if ($re){
            $db_config = get_db_config(true);
            $lvcfg = $db_config['user_leval_cfg'];
            //是否带有登录信息
            $token = input('token');
            $uid = input('uid');
            $uinfo = model('User')->get(['uid'=>$uid,'token'=>$token]);
            $leval = 0;
            if ($uinfo){
                $leval = $uinfo->getData('leval');
            }
            $zi_cfg = $lvcfg['zigou'];
            foreach ($re['data'] as $k=>$v){
                //预估赚以及升级赚,取自购
                $earn_yg = 0;
                if ($leval>=0){
                    $earn_yg = round($v['price_after_quan']*$v['rate']*$zi_cfg[$leval]/10000,2);
                }
                //升级赚,直接取分公司
                $re['data'][$k]['earn_sj'] = round($v['price_after_quan']*$v['rate']*$zi_cfg[3]/10000,2);
                $re['data'][$k]['earn_yg'] = $earn_yg;
            }
            $this->success('获取成功','',$re);
        }else {
            if (input('p')==1){
                $this->result('',2,'没有啦,不开森-_-!');
            }
            $this->error('没有啦,不开森-_-!');
        } 
    }
    /**
     * 淘宝 新搜索  (通用物料搜索API（导购）)，使用中
     */
    protected function taobao(){
        $q = trim(input('q',''));
        $p = input('p',1);
        //监听url搜索
        //监听淘口令搜索
        if (!empty($q)){
            $match_re = preg_match("/￥.*￥/",$q,$match_arr);
            if ($match_re>0 && $p==1){
                $tk = new \ddj\Tk();
                $item_id = $tk->get_token($match_arr[0]);
                if ($item_id){
                    $goods = new Goods();
                    $info = $goods->taobao_item_info($item_id);
                    if ($info){
                        $info['tjp'] = 't';
                        $info['short_title'] = $info['title'];
                        unset($info['desc_cb']);
                        return [
                            'data'=>[$info]
                        ];
                    }
                }
            }
        }
        $sort_type = input('sort','default');
        $desc = input('desc','');
        $is_quan = input('is_quan','false');
        $options = [
            'page_size' => "20",
            'q' => $q,
        ];
        //分页
        $options['page_no'] = $p;
        //是否有券
        if ($is_quan=='true' || $is_quan==1){
            $options['has_coupon'] = "true";
        }
        //排序
        if ($sort_type=='sales'){//销量排序
            if ($desc=='up'){
                $options['sort'] = "total_sales_asc";
            }else {
                $options['sort'] = "total_sales_des";
            }
        }elseif ($sort_type=='price'){//价格排序
            if ($desc=='up'){
                $options['sort'] = "price_asc";
            }else {
                $options['sort'] = "price_des";
            }
        }elseif ($sort_type=='is_tmall'){
            $options['is_tmall'] = "true";
        }elseif ($sort_type=='new'){//最新
            $options['sort'] = "tk_total_sales_des";
        }elseif ($sort_type=='rate'){//佣金
            $options['sort'] = "tk_rate_des";
        }
        
        $tk = new \ddj\Tk($options);
        $res = $tk->optional();
        //换格式
        if ($res['total_results']>0){
            //获取配置
            $db_config = get_db_config(true);
            $lvcfg = $db_config['user_leval_cfg'];
            $return = [
                'config' => '',
            ];
            foreach ($res['result_list']['map_data'] as $v){
                $temp = [
                    'tjp' => 't',
                    'search' => 1,
                    'title' => $v['title'],
                    'short_title' => $v['short_title'],
                    'item_id' => $v['num_iid'],
                    'is_tmall' => $v['user_type'],
                    'is_tmall_text' => $v['user_type']==1 ? '天猫' : '淘宝',
                    'rate' => $v['commission_rate']/100,
                    'quan_price' => 0,
                    'price' => $v['zk_final_price'],
                    'sales' => $v['volume'],
                    'shop_title' => $v['shop_title'] ? $v['shop_title'] : '&nbsp;',
                    'pic' =>$v['pict_url'],//.'_200x200.jpg',
                    'url' => 'https:' . (isset($v['coupon_share_url']) ? $v['coupon_share_url'] : $v['url']),//高佣链接
                    'coupon_start_time' => $v['coupon_start_time'],
                    'coupon_end_time' => $v['coupon_end_time'],
                    'coupon_total_count' => $v['coupon_total_count'],
                    'coupon_remain_count' => $v['coupon_remain_count'],
                ];
                if (is_string($v['coupon_info'])){
                    $temp['quan_price'] = get_coupon_price($v['coupon_info']);
                }
                $temp['price_after_quan'] = round($temp['price'] - $temp['quan_price'],2);
                
                $return['data'][] = $temp;
            }
            return $return;
        }else {
            return false;
        }
    }
    
    /**
     * 京东搜索
     * 此接口为接用
     */
    protected function jd()
    {
        $q = trim(input('q','女装'));
        $p = input('p',1);
        $sort_type = input('sort','default');
        $desc = input('desc','');
        $options = [
            //'appkey' => '83EDF510BE87DDB8177F6FC8C8303216',
            //'appsecret' => '930be0abb755477094a68515b1e85d2c',
            //'accesstoken' => 'a0e2e67d-e415-4cc2-9aa4-7dc6d0801699',
            'pageSize' => 20,
            'q' => $q,
        ];
        //分页
        $options['pageIndex'] = $p;
        //排序TODO 因此接口无排序功能，固..
        //接口查询
        $jd = new \ddj\Jd($options);
        $res = $jd->query_coupon_goods();
        //换格式
        if ($res['query_coupon_goods_result']['total']>0){
            //获取配置
            $db_config = get_db_config(true);
            $lvcfg = $db_config['user_leval_cfg'];
            $return = [
                'config' => '',
            ];
            foreach ($res['query_coupon_goods_result']['data'] as $v){
                $temp = [
                    'tjp' => 'j',
                    'search' => 1,
                    'title' => $v['skuName'],
                    'short_title' => $v['skuName'],
                    'item_id' => $v['skuId'],
                    'is_tmall' => 2,
                    'is_tmall_text' => '京东',
                    'rate' => $v['wlCommissionShare'],
                    'quan_price' => $v['couponList'][0]['discount'] ?? 0,
                    'price' => $v['wlPrice'],
                    'sales' => $v['inOrderCount'],
                    'shop_title' => '',
                    'pic' => 'https://img11.360buyimg.com/n1/'.$v['imageurl'],//'https://img11.360buyimg.com/n1/s200x200_'.$v['imageurl'],
                    'url' => $v['couponList'][0]['link'],//券链接
                    'coupon_start_time' => date('Y-m-d',substr($v['couponList'][0]['beginTime'], 0,-3)),
                    'coupon_end_time' => date('Y-m-d',substr($v['couponList'][0]['endTime'], 0,-3)),
                    'coupon_total_count' => 0,//京东无此参数
                    'coupon_remain_count' => 0,
                ];
                if (strpos($temp['url'], 'http')===false){
                    $temp['url'] = 'https:'.$temp['url'];
                }
                $temp['price_after_quan'] = round($temp['price'] - $temp['quan_price'],2);
                $return['data'][] = $temp;
            }
            return $return;
        }else {
            return false;
        }
    }
    /**
     * 拼夕夕
     */
    protected function pdd()
    {
        $q = trim(input('q',''));
        $p = input('p',1);
        $sort_type = input('sort','0');
        $desc = input('desc','');
        $is_quan = input('is_quan','false');
        $cid = input('cid');
        $options = [
            'type' => 'pdd.ddk.goods.search',
            'keyword' => $q,
            'page' => $p,
            'page_size' => 20,
            'with_coupon' => 'true',
            'sort_type' => 0,
        ];
        if ($cid>0){
            $options['opt_id'] = $cid;
        }
        //是否有券
        if ($is_quan=='true' || $is_quan==1){
            $options['with_coupon'] = 'false';
        }
        //排序
        if ($sort_type=='sales'){//销量排序
            if ($desc=='up'){
                $options['sort_type'] = 5;
            }else {
               
                $options['sort_type'] = 6;
            }
        }elseif ($sort_type=='price'){//价格排序
            if ($desc=='up'){
                $options['sort_type'] = 3;
            }else {
                $options['sort_type'] = 4;
            }
        }elseif ($sort_type=='new'){//最新
            $options['sort_type'] = 12;
        }elseif ($sort_type=='rate'){//佣金
            $options['sort_type'] = 2;
        }
        //接口查询
        $pdd = new \ddj\Pdd($options);
        $res = $pdd->request();
        //换格式
        if ($res['goods_search_response']['total_count']>0){
            //获取配置
            $db_config = get_db_config(true);
            $lvcfg = $db_config['user_leval_cfg'];
            $return = [
                'config' => '',
            ];
            foreach ($res['goods_search_response']['goods_list'] as $v){
                $temp = [
                    'tjp' => 'p',
                    'search' => 1,
                    'title' => $v['goods_name'],
                    'short_title' => $v['goods_name'],
                    'item_id' => $v['goods_id'],
                    'is_tmall' => 3,
                    'is_tmall_text' => '拼多多',
                    'rate' => $v['promotion_rate']/10,
                    'quan_price' => $v['coupon_discount'] ? $v['coupon_discount']/100 : 0,
                    'price' => $v['min_group_price']/100,
                    'sales' => $v['sold_quantity'],
                    'shop_title' => $v['mall_name'],
                    'pic' => $v['goods_thumbnail_url'],
                    'url' => '',//券链接
                    'coupon_start_time' => date('Y-m-d',$v['coupon_start_time']),
                    'coupon_end_time' => date('Y-m-d',$v['coupon_end_time']),
                    'coupon_total_count' => $v['coupon_total_quantity'],
                    'coupon_remain_count' => $v['coupon_remain_quantity'],
                ];
                $temp['price_after_quan'] = round($temp['price'] - $temp['quan_price'],2);
                $return['data'][] = $temp;
            }
            //dump($return);
            return $return;
        }else {
            return false;
        }
    }
    
    /**
     * 京东列表
     * 调用京推推
     */
    public function jd_list()
    {
        $page = (int)input('p',1);
        $cid = (int)input('cid','');
        $options = [
            'page' => $page,
        ];
        if ($cid>0 && $cid<=11){
            $options['type'] = $cid;
        }
        //接口查询
        $jd = new \ddj\Jd($options);
        $res = $jd->jtt_goods_list();
        if ($res){
            $db_config = get_db_config(true);
            $lvcfg = $db_config['user_leval_cfg'];
            //是否带有登录信息
            $token = input('token');
            $uid = input('uid');
            $uinfo = model('User')->get(['uid'=>$uid,'token'=>$token]);
            $leval = 0;
            if ($uinfo){
                $leval = $uinfo->getData('leval');
            }
            $zi_cfg = $lvcfg['zigou'];
            foreach ($res as $k=>$v){
                //预估赚以及升级赚,取自购
                $earn_yg = round($v['price_after_quan']*$v['rate']*$zi_cfg[$leval]/10000,2);
                //升级赚,直接取分公司
                $res[$k]['earn_sj'] = round($v['price_after_quan']*$v['rate']*$zi_cfg[3]/10000,2);
                $res[$k]['earn_yg'] = $earn_yg;
            }
            $this->success('获取成功','',$res);
        }else {
            $this->error('没有更多了');
        }
    }
    /**
     * 发圈
     */
    public function faquan()
    {
        $min_id = input('min_id',1);
        $tk = new \ddj\Tk();
        $res = $tk->faquan($min_id);
        if ($res){
            //dump($res);die;
            $this->success('获取成功','',$res);
        }else {
            $this->error('没有更多了');
        }
    }
    /**
     * 拼多多-查询商品标签列表
     */
    public function pdd_opt()
    {
        $cache_data = cache('pdd_opt');
        if ($cache_data){
            $this->success('获取成功','',$cache_data);
        }
        $options = [
            'type' => 'pdd.goods.opt.get',
            'parent_opt_id' => 0,
        ];
        //接口查询
        $pdd = new \ddj\Pdd($options);
        $res = $pdd->request();
        $list = $res['goods_opt_get_response']['goods_opt_list'];
        $list = $list ??[];
        if (isset($list) && count($list)>0){
            cache('pdd_opt',$list);
            $this->success('获取成功','',$list);
        }else {
            $this->error('获取失败');
        }
        
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}
